<?php
/**
 * Created by PhpStorm.
 * User: yzr
 * Date: 1/27/2021
 * Time: 15:19
 */
namespace app\common\model\file;

use app\common\model\base\A3Mall;

class Association extends A3Mall
{
    protected $name = "file_association";

    protected $type = [
        "id"=>"integer",
        "association_type"=>"integer",
        "association_id"=>"integer",
        "filename"=>"string",
        "status"=>"integer",
        "create_time"=>"integer",
        "update_time"=>"integer",
    ];
    const STATUS_DELETE = 0;    //取消
    const STATUS_EFFECTIVE = 1; // 有效

    const ASSOCIATION_TYPE_LIST = [
        'job'   => 1,   //任务图片验证示例
        'jobtake'   => 2,   //需求图片
    ];


    /**
     * 通过任务ID添加多张图片
     * @param $id
     * @param $filenames
     * @return int
     */
    public function recordInsertListByJob($id,$filenames)
    {
        return $this->recordInsertList($filenames,static::ASSOCIATION_TYPE_LIST['job'],$id);
    }

    /**
     * 通过 JOB id删除图片
     * @param $jobId
     */
    public function recordDeleteByJobId($jobId) {
        return $this->recordDeleteByTypeId(static::ASSOCIATION_TYPE_LIST['job'],$jobId);
    }

    /**
     * 通过接单任务ID添加多张图片
     * @param $id
     * @param $filenames
     * @return int
     */
    public function recordInsertListByOrderTake($id,$filenames)
    {
        return $this->recordInsertList($filenames,static::ASSOCIATION_TYPE_LIST['jobtake'],$id);
    }


    /**
     * 通过类型及ID删除图片
     * @param $type 类型
     * @param $id   id
     */
    private function recordDeleteByTypeId($type,$id)
    {
        return $this->where([
            'association_type'  => $type,
            'association_id'    => $id,
        ])->update([
            'status'    => static::STATUS_DELETE,
            'update_time'   => time()
        ]);
    }


    /**
     * 插入文件关联
     * @param $filenames 文件列表
     * @param $type 类型
     * @param $id 关联ID
     * @return int
     */
    private function recordInsertList($filenames,$type,$id) {
        $time = time();
        $default = [
            'association_type'  => $type,
            'association_id'    => $id,
            'filename'    => '',
            'status'    => static::STATUS_EFFECTIVE,
            'create_time'  => $time,
            'update_time'  => $time,
        ];
        $list = array_map(function ($filename) use($default){
            $default['filename'] = $filename;
            return $default;
        },is_array($filenames)?$filenames:[$filenames]);
        return $this->insertAll($list);
    }


}
